//  src/utils/request.ts
import axios, { type InternalAxiosRequestConfig, type AxiosResponse } from "axios";
import { httpsUrl } from "@/utils/httpsUrl";
// 创建 axios 实例
const service = axios.create({
  baseURL: httpsUrl.API_URL,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const accessToken = localStorage.getItem("TOKEN_KEY");
    if (accessToken) {
      config.headers["Authorization"] = "Bearer " + accessToken;
      config.headers["token"] = accessToken;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, msg } = response.data;
    if (code == 1) {
    } else {
      ElMessage.error(msg || "系统出错");
    }
    return response.data;
  },
  (error: any) => {
    if (error.response.data) {
      const { code, msg } = error.response.data;
      // token 过期，跳转登录页
      if (code === "A0230") {
      } else {
        ElMessage.error(msg || "系统出错");
      }
    }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default service;
